package com.book.bookmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.bookmanage.config.execption.CustomException;
import com.book.bookmanage.constant.ResponseEnum;
import com.book.bookmanage.mapper.MenuMapper;
import com.book.bookmanage.model.dto.MenuDto;
import com.book.bookmanage.model.entity.Menu;
import com.book.bookmanage.service.MenuService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

@Service
public class MenuServiceImpl implements MenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public void insertMenu(MenuDto menu) {
        QueryWrapper<Menu> existWrapper = new QueryWrapper<>();
        existWrapper.eq("url", menu.getUrl());
        Menu isExist = menuMapper.selectOne(existWrapper);
        if(isExist != null) {
            throw new CustomException(ResponseEnum.DATA_EXIST);
        }
        QueryWrapper<Menu> pExistWrapper = new QueryWrapper<>();
        pExistWrapper.eq("menu_id", menu.getParentId());
        Menu isPExist = menuMapper.selectOne(pExistWrapper);
        System.out.println(isPExist);
        if(!menu.getParentId().equals(BigInteger.ZERO) && isPExist == null) {
            throw new CustomException(ResponseEnum.PARENT_DATA_NOT_EXIST);
        }
        Menu insertMenu = new Menu();
        insertMenu.setMenuName(insertMenu.getMenuName());
        BeanUtils.copyProperties(menu, insertMenu);
        int insert = menuMapper.insert(insertMenu);
        if(insert == 0) {
            throw new CustomException(ResponseEnum.INSERT_FAILED);
        }
    }
}
